<script setup lang="ts">
defineOptions({
  name: "Welcome"
});
import { UserFilled, Tickets, Cpu } from "@element-plus/icons-vue";
import { onMounted, ref, reactive, toRefs } from "vue";
import { getServer, getVersion } from "@/api/server";
import { getUserList, getUserInfoV1, getUserContainer } from "@/api/user";
import { getOrderList, getUserOrderList } from "@/api/order";
import { getWorkSheetList } from "@/api/worksheet";
import { getUserMessageList } from '../../api/message'
import { message } from "@/utils/message";
import { useRouter} from 'vue-router';
import Bulletin from '@/components/MessTable/bulletin.vue';
import { pay_request, uploadAvatar } from "@/api/user";
import { mainUrl } from "@/api/utils";
const state = reactive({
  circleUrl:
    'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  squareUrl:
    'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
  sizeList: ['small', '', 'large'] as const,
})

const { circleUrl, squareUrl, sizeList } = toRefs(state);
const showTip = ref(false);
const NewVersion = ref(false);
const version = ref('');
const newContent= ref('')
const checkVersionNotification = async () => {
  try {
    const res = await getVersion();
    if (res.data.code === 201) {
      NewVersion.value = true;
      console.log('版本', res.data.data);
      version.value = res.data.data.version;
      newContent.value = res.data.data.info;
    }
  } catch (error) {
    console.error('Error checking for new version:', error);
  }
};

onMounted(async () => {
  //获取版本更新
  if (router.options.history.state.back=='/login'&&user_type==1) {
    console.log('上个路由',router.options.history.state.back);
    checkVersionNotification();
  }
  
  user_id.value = localStorage.getItem("user_id");
  let res = await getServer(1, 5, search.value);
  tableData.value = res.data.data;
  serverNum.value = res.data.count;
  //用户信息
  await getUserInfo();
  getOrder();
  getContainer();
  getList()
  await getbulletin();
  //用户数量
  let result = await getUserList({ page: 1, count: 10, key: "" });
  userNum.value = result.data.count;
  //订单数量
  let res2 = await getOrderList({ page: 1, count: 10, key: "" });
  orderNum.value = res2.data.count;
  //工单列表
  let res3 = await getWorkSheetList({
    page: 1,
    count: 3,
    user_id: ''
  });
  activities.value = res3.data.data.map(item => {
    return {
      content: item.title,
      timestamp: item.created_at,
      sheet_id: item.sheet_id,
      type:
        item.state == 0
          ? "warning"
          : item.state == 1
            ? "primary"
            : item.state == 2
              ? "success"
              : item.state == 3
                ? "info"
                : ""
    };
  });
});
//获取用户信息
const userID = ref(0);
const getUserInfo = async () => {
  let userRes = await getUserInfoV1();
  userInfo.value = userRes.data.data;
  avatar.value = `${mainUrl}/v1/attachment/get_attachment?aid=${userInfo.value.avatar}`;
  userID.value = userRes.data.data.user_type;
}
const avatar = ref();
const search = ref("");
let tableData = ref([]);
const user_id = ref("");
const user_type = localStorage.getItem("user_type");
const userInfo = ref({})
//服务器数量
const serverNum = ref(0);
const userNum = ref(0);
const orderNum = ref(0);
const activities = ref([]);
const comp = ref(null)
//用户相关信息
const contentID = async () => {
  await comp.value.someMethod()
}
const getbulletin = async () => {
  let id = localStorage.getItem("bulletinId")
  let res = await getUserMessageList({ page: 1, count: 5, message_type: "官方公告" });
  if (res.data.data[0]) {
    if (res.data.data[0].message_id != id && userID.value != 1) {
      console.log(userID.value)
      localStorage.setItem("bulletinId", res.data.data[0].message_id);
      contentID()
    }
  }
}
const userOrder = ref();
const userContainer = ref();
const getOrder = async () => {
  let res = await getUserOrderList({ page: 1, count: 5, key: "" });
  userOrder.value = res.data.data;
  console.log('订单', res.data.data);
}
const getContainer = async () => {
  let res = await getUserContainer({ page: 1, count: 5, key: "" });
  userContainer.value = res.data.data;
  console.log('容器', res.data.data);
}
const innerMessage = ref([]);
const activity = ref([]);
const news=ref([])
const getList = async () => {
  let res = await getUserMessageList({ page: 1, count: 5, message_type: "官方公告" });
  innerMessage.value = res.data.data
  let res2 = await getUserMessageList({ page: 1, count: 5, message_type: "官方政策" });
  activity.value = res2.data.data
  let res3 = await getUserMessageList({ page: 1, count: 5, message_type: "新闻资讯" });
  news.value = res3.data.data
}
const router = useRouter()
const handleRowClick = (data) => {
  router.push(`/news/messagedetail?message_id=${data}`)
}
//支付订单
const pay_url = ref('');
const pay_dialog = ref(false);
const pay_src = ref('');
const pay = async (data) => {
  if (data.trade_state == 0) {
    pay_request({ pay_type: data.pay_type, trade_id: data.trade_id }).then(res => {
      console.log(res, '准备支付');
      if (res.data.code == 200) {
        message('购买成功！', { type: 'success' });
        getOrder();

      } else if (res.data.data.type == 'html') {
        pay_url.value = res.data.data.html;
        pay_dialog.value = true;
      } else {
        pay_src.value = res.data.data.img;
        pay_dialog.value = true;
      }
    })
  }
}
//头像
const onFileSelected = (event) => {
  const file = event.target.files[0];
  if (file) {
    uploadAvatar({ file: file }).then((res) => {
      console.log('上传文件', res)
      if (res.data.code == 200) {
        message('上传成功', { type: 'success' });
        getUserInfo();
      } else {
        message(res.data.msg, { type: 'error' });
      }
    })
  }
}
const handleMouseEnter = () => {
  showTip.value = true;
};
const handleMouseLeave = () => {
  showTip.value = false;
}
// 管理员服务器点击
const handleSeleUserId = (a) => {
  router.push(`/servers/server?server_id=${a.server_id}`)
}

</script>

<template>
  <div class="index_body">
    <el-row :gutter="20" v-if="user_type == '1'">
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8" style="margin-bottom: 20px">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">用户数量</el-col>
            <el-col :span="12" style="text-align: right">
              <el-avatar :icon="UserFilled" style='background-color: #409eff;' />
            </el-col>
          </el-row>

          <el-row justify="space-between">
            <el-col :span="12">
              <el-statistic title="实时用户数量" :value="userNum" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8" style="margin-bottom: 20px;">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">订单数量</el-col>
            <el-col :span="12" style="text-align: right">
              <el-avatar :icon="Tickets" style='background-color:#57d149;' />
            </el-col>
          </el-row>

          <el-row justify="space-between">
            <el-col :span="12">
              <el-statistic title="实时订单数量" :value="orderNum" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">服务器数量</el-col>
            <el-col :span="12" style="text-align: right">
              <el-avatar :icon="Cpu" style='background-color: #ffb440;' />
            </el-col>
          </el-row>

          <el-row justify="space-between">
            <el-col :span="12">
              <el-statistic title="实时服务器数量" :value="serverNum" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" v-if="user_type == '0'">
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8" style="margin-bottom: 20px">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">用户信息</el-col>
            <!-- <div class="block">
              <el-avatar :size="50" :src="circleUrl" class="avatar-hover" />
            </div> -->
            <div class="block" @mouseenter="handleMouseEnter" @mouseleave="handleMouseLeave">
              <el-avatar :size="50" :src="avatar ? avatar : circleUrl" class="avatar-hover"
                @click="$refs.fileInput.click()" />
              <div class="change-avatar-tip" v-if="showTip">点击修改头像</div>
              <input type="file" ref="fileInput" @change="onFileSelected" style="display:none" />
            </div>
          </el-row>
          <el-row justify="space-between">
            <el-col :span="12">
              <el-statistic title="用户名" :value="userInfo.username" />
            </el-col>
          </el-row>
          <el-row justify="space-between">
            <el-col :span="12">
              <el-statistic title="账户余额" :value="userInfo.balance+' 元'" />
              <el-button plain type="primary"><router-link :to="'/order/recharge'">充值</router-link></el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8" style="margin-bottom: 20px;">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">订单信息</el-col>
            <el-col :span="12" style="text-align: right">
              <el-avatar :icon="Tickets" :size="50" style='background-color:#57d149;' />
            </el-col>
          </el-row>
          <div v-for="item in userOrder" style="margin-bottom: 10px">
            <span>订单号：{{ item.trade_id }}</span> <el-tag @click="pay(item)"
              :type="item.trade_state == 0 ? 'warning' : 'success'" style="margin-left: 10px;cursor:pointer">{{
              item.trade_state == 0 ? '未支付' : '已支付' }}</el-tag>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8">
        <el-card class="card" style="height: 350px;">
          <el-row justify="space-between">
            <el-col :span="12">容器信息</el-col>
            <el-col :span="12" style="text-align: right">
              <el-avatar :icon="Cpu" :size="50" style='background-color: #ffb440;' />
            </el-col>
          </el-row>
          <div v-for="item in userContainer" style="margin-bottom: 10px;display: flex;">
            <span class='mess-row'
              style="cursor:pointer;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;display: block;width: 250px;"
              @click="router.push(`/self/container?container_id=${item.container_id}`)">容器ID：{{ item.container_id
              }}</span>
            <el-tag :type="item.container_state == 0 || item.container_state == 1
              ? 'info'
              : item.container_state == 2
                ? 'success'
                : 'danger'
              ">{{
              item.container_state == 0
              ? "未支付"
              : item.container_state == 1
              ? "未开通"
              : item.container_state == 2
              ? "开机"
              : "关机"
              }}</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 管理员工单列表 -->
    <el-row :gutter="20" v-if="user_type == '1'">
      <el-col :xs="30" :sm="30" :md="16" :lg="16" :xl="16" style="margin-bottom: 20px;">
        <el-card class="card" style="height: 350px;">
          <h4>我的服务器</h4>
          <br />
          <div class="table_box">
            <el-table class="table_el" :data="tableData" style="width: auto" @row-click="handleSeleUserId" height="210">
              <el-table-column label="ID" prop="server_id" show-overflow-tooltip />
              <el-table-column label="服务器名称" prop="name" show-overflow-tooltip />
              <el-table-column label="IP" prop="server_ip" show-overflow-tooltip />
              <el-table-column>
                <template #header>状态</template>
                <template #default="scope">
                  <el-tag v-if="scope.row.state == 1" type="success">在线</el-tag>
                  <el-tag v-if="scope.row.state == 0" type="danger">离线</el-tag>
                </template>
              </el-table-column>
            </el-table>

            <div class="table_pagination">
              <el-button style="margin-top: 10px;" type="primary" plain><router-link
                  :to="'/servers/servers'">查看更多服务器</router-link>
              </el-button>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="8" :xl="8">
        <el-card class="card" style="height: 350px;">
          <h4>工单列表</h4>
          <br />
          <el-timeline style="max-width: 600px">
            <el-timeline-item style="cursor:pointer;" v-for="(activity, index) in activities" :key="index"
              :type="activity.type" :timestamp="activity.timestamp">
              <span class="mess-row" @click='router.push(`/workSheet/workContent?sheet_id=${activity.sheet_id}`)'>{{
                activity.content }}</span>
            </el-timeline-item>
          </el-timeline>
          <el-button type="primary" plain><router-link :to="'/workSheet/workSheet'">查看更多工单</router-link></el-button>
        </el-card>
      </el-col>
    </el-row>
    <!-- 用户工单列表 -->
    <el-row :gutter="20" v-if="user_type == '0'">
      <el-col :xs="30" :sm="30" :md="10" :lg="6" :xl="6" style="margin-bottom: 20px;">
        <el-card class="card" style="height: 350px;">
          <h4>工单列表</h4>
          <br />
          <el-timeline style="max-width: 600px">
            <el-timeline-item style="cursor:pointer;" v-for="(activity, index) in activities" :key="index"
              :type="activity.type" :timestamp="activity.timestamp">
              <span class="mess-row" @click='router.push(`/workSheet/workContent?sheet_id=${activity.sheet_id}`)'>{{
                activity.content }}</span>
            </el-timeline-item>
          </el-timeline>
          <el-button type="primary" plain><router-link :to="'/workSheet/workSheet'">查看更多工单</router-link></el-button>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="6" :xl="6" style="margin-bottom: 20px;">
        <el-card class="card" style="height: 350px;">
          <h4>官方公告</h4>
          <br />
          <el-table :data="innerMessage" style="width: 100%">
            <el-table-column label="标题">
              <template #default="scope">
                <div class="mess-row" @click="handleRowClick(scope.row.message_id)" style="cursor:pointer;">
                  {{ scope.row.title }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="时间" prop="created_at" />
          </el-table>
          <el-button type="primary" style="margin-top: 10px;" plain><router-link
              :to="'/self/message'">查看更多公告</router-link></el-button>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="6" :xl="6">
        <el-card class="card" style="height: 350px;">
          <h4>官方政策</h4>
          <br />
          <el-table :data="activity" style="width: 100%">
            <el-table-column label="标题">
              <template #default="scope">
                <div class="mess-row" @click="handleRowClick(scope.row.message_id)" style="cursor:pointer;">
                  {{ scope.row.title }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="时间" prop="created_at" />
          </el-table>
          <el-button type="primary" style="margin-top: 10px;" plain><router-link
              :to="'/self/activity'">查看更多政策</router-link></el-button>
        </el-card>
      </el-col>
      <el-col :xs="30" :sm="30" :md="10" :lg="6" :xl="6">
        <el-card class="card" style="height: 350px;">
          <h4>新闻资讯</h4>
          <br />
          <el-table :data="news" style="width: 100%">
            <el-table-column label="标题">
              <template #default="scope">
                <div class="mess-row" @click="handleRowClick(scope.row.message_id)" style="cursor:pointer;">
                  {{ scope.row.title }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="时间" prop="created_at" />
          </el-table>
          <el-button type="primary" style="margin-top: 10px;" plain><router-link
              :to="'/self/activity'">查看更多新闻</router-link></el-button>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog title='支付' v-model="pay_dialog" style="width: 90%;height:1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100% ;height:800px" v-if="pay_url != ''"></iframe>
      <img :src="pay_src" v-else />
    </el-dialog>
    <Bulletin ref="comp"></Bulletin>
    <el-dialog title='更新提示' v-model="NewVersion">
      <div class="newcon">
        <div>有新版本，请及时更新</div>
        <div style="margin: 10px 0;">版本:{{ version }}</div>
        <div>更新内容:{{ newContent }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.index_body .el-row {
  margin-bottom: 20px;
}

.mess-row:hover {
  color: #409EFF
}

.avatar-hover {
  transition: transform 0.3s;
}

.avatar-hover:hover {
  transform: scale(1.5);
}

.change-avatar-tip {
  position: absolute;
  right: 29px;
  width: 100px;
  height: 25px;
  line-height: 25px;
  font-size: 12px;
  border-radius: 5px;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  cursor: pointer;
  /* opacity: 0; */
  transition: opacity 0.3s;
  /* 添加过渡效果 */
  z-index: 1;
}

.change-avatar-tip:hover {
  opacity: 1;
}
.newcon{
  padding: 10px 0 20px;}
</style>
